package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//地址管理
@Slf4j
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    /**
     * 新增
     * @param addressBook
     * @return
     */
    @PostMapping
    public R<AddressBook> save(@RequestBody AddressBook addressBook){
        //调用BaseContext.getThreadLocal()方法从线程中获取保存的登录用户id
        addressBook.setUserId(BaseContext.getThreadLocal());
        //如果用户新增第一条地址，直接将其设为默认地址
        LambdaQueryWrapper<AddressBook> lqw =new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getUserId,addressBook.getUserId());
        int count = addressBookService.count(lqw);
        if(count==0){
            //将第一条地址设为默认
            addressBook.setIsDefault(1);
            addressBookService.save(addressBook);
        } else{
            //如果不是第一条直接调用save方法进行添加地址


            addressBookService.save(addressBook);
        }
        return R.success(addressBook);
    }

    /**
     * 查询指定用户的全部地址(添加地址后跳转到此方法查询的页面)
     * @param addressBook
     * @return
     */
    @GetMapping("/list")
    public R<List<AddressBook>> list(AddressBook addressBook){
        //调用BaseContext.getThreadLocal()方法获取用户id
        addressBook.setUserId(BaseContext.getThreadLocal());
        //创建条件构造器
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        //根据用户id去查询地址
        lqw.eq(addressBook.getUserId() != null,AddressBook::getUserId,addressBook.getUserId());
        //根据修改地址的时间进行降序排序(即最新修改的地址数据在最上面显示)
        lqw.orderByDesc(AddressBook::getIsDefault).orderByDesc(AddressBook::getUpdateTime);
        return R.success(addressBookService.list(lqw));

    }

    /**
     * 根据id查询地址(修改地址时回显)
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R get(@PathVariable Long id){
        //调用getById方法获取该id所对应的地址信息对象
        AddressBook addressBook = addressBookService.getById(id);
        //对该对象进行判断
        if (addressBook != null){
            //不为空，返回该id所对应的地址信息
            return R.success(addressBook);
        }else {
            //为空时返回错误提示信息
            return R.error("没有地址信息");
        }
    }

    /**
     * 设置默认地址
     * @param addressBook
     * @return
     */
    @PutMapping("/default")
    public R<AddressBook> setdefault(@RequestBody AddressBook addressBook){
        /*//条件构造器
        LambdaQueryWrapper<AddressBook> lqws = new LambdaQueryWrapper<>();
        //获取原来的默认地址
        lqws.eq(AddressBook::getUserId,addressBook.getUserId()).eq(AddressBook::getIsDefault,1);
        AddressBook book1 = addressBookService.getOne(lqws);
        //判断book1是否存在默认地址
        if (book1 != null){
            //存在，取消原来默认地址
            book1.setIsDefault(0);
            addressBookService.updateById(book1);
        }
        //条件构造器
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        //获取当前登录用户的所有地址信息的id
        lqw.eq(addressBook.getUserId() != null,AddressBook::getUserId,BaseContext.getThreadLocal());
        //获取前端传来的需要修改为默认地址的那条地址信息的id
        lqw.eq(AddressBook::getId,addressBook.getId());
        //根据条件查询地址信息的对象
        AddressBook book = addressBookService.getOne(lqw);
        //将这条地址信息的对象的IsDefault字段设为1
        book.setIsDefault(1);
        //修改为默认地址
        addressBookService.updateById(book);

        return R.success(addressBook);*/

        //条件构造器
        LambdaUpdateWrapper<AddressBook> lqw = new LambdaUpdateWrapper<>();
        //获取当前登录用户的所有地址信息的id
        lqw.eq(addressBook.getUserId() != null,AddressBook::getUserId,BaseContext.getThreadLocal());
        //设置当前登录用户的所有地址信息的isDefault字段为0(也就是都设为不是默认地址)
        lqw.set(AddressBook::getIsDefault,0);
        addressBookService.update(lqw);
        //将前端传过来的地址信息设置为默认地址
        addressBook.setIsDefault(1);
        //更新
        addressBookService.updateById(addressBook);
        return R.success(addressBook);


    }

    /**
     * 查询默认地址
     * @return
     */
    @GetMapping("default")
    public R<AddressBook> getDefault(){
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getUserId,BaseContext.getThreadLocal()).eq(AddressBook::getIsDefault,1);
        AddressBook addressBook = addressBookService.getOne(lqw);
        if(addressBook != null){
            return R.success(addressBook);
        }else {
            return R.error("没有默认地址");
        }
    }

    /**
     * 修改用户地址
     * @param addressBook
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody AddressBook addressBook){
        if (addressBook ==null){
            return R.error("地址信息不存在");
        }
        addressBookService.updateById(addressBook);
        return R.success("地址修改成功");
    }



    @DeleteMapping
    public R<String> delete( Long ids){
        AddressBook addressBook =null;
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        //通过查询用户id和要删除的地址id，删除地址
        lqw.eq(AddressBook::getId,ids).eq(AddressBook::getUserId,BaseContext.getThreadLocal());
        addressBookService.remove(lqw);

        //删除地址后根据修改时间降序排序自动设置最新修改时间的那条地址为默认地址
        LambdaQueryWrapper<AddressBook> lqwe = new LambdaQueryWrapper<>();
        lqwe.eq(AddressBook::getUserId,BaseContext.getThreadLocal());
        lqwe.orderByDesc(AddressBook::getUpdateTime);
        List<AddressBook> list = addressBookService.list(lqwe);
        int count = addressBookService.count(lqwe);

        if (count != 0){
            addressBook= list.get(0);
            addressBook.setIsDefault(1);
            addressBookService.updateById(addressBook);
        }


        //删除地址后，判断用户地址是否还剩最后一条，若为最后一条，自动设置为默认地址
        LambdaQueryWrapper<AddressBook> lss = new LambdaQueryWrapper<>();
        lss.eq(AddressBook::getUserId,BaseContext.getThreadLocal());
        List<AddressBook> list1 = addressBookService.list(lss);
        if (list1.size() == 1 ){
            addressBook.setIsDefault(1);
            addressBookService.updateById(addressBook);
        }
        return R.success("删除地址成功");
    }

}
